package com.tusuo.stds.ui.main;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.tusuo.stds.Constants;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.biz.CurrentUser;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.rest.SceneList;
import com.tusuo.stds.rest.UploadResponse;
import com.tusuo.stds.rest.UserInfo;
import com.tusuo.stds.ui.lab.LabActivity_;
import com.tusuo.stds.ui.login.ThirdLoginUserInfo;
import com.tusuo.stds.ui.scenedetail.SceneDetailActivity_;
import com.tusuo.stds.ui.similarity.SimilarityTempActivity_;
import com.tusuo.stds.util.DialogUtils;
import com.tusuo.stds.util.DoubleClickExitDetector;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.parceler.Parcels;

import java.io.File;
import java.util.ArrayList;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import myandroid.library.util.ApplicationHelper;
import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(MainActivity.class)
@EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {

    private static final int APP_PERMISSION = 100;

    @Inject
    DoubleClickExitDetector mDoubleClickExitDetector;
    @Inject
    CurrentUser mCurrentUser;
    @Inject
    SharedPreferences mSharedPref;
    @Inject
    ApiHelper aHelper;

    @ViewById(R.id.tab_layout)
    CommonTabLayout mTabLayout;

    @ViewById(R.id.main_layout_guide)
    RelativeLayout layoutGuide;

    private boolean permissionTip = true;

    private ArrayList<Fragment> mFragmentList = new ArrayList<>();

    private String[] mTitles = {"闯关", "发现","错题本", "我"};

    private int[] mIconUnselectedIds = {
            R.drawable.tab_challenge_unselected,
            R.drawable.tab_find_unselected,
            R.drawable.tab_bank_unselected,
            R.drawable.tab_me_unselected
    };

    private int[] mIconSelectedIds = {
            R.drawable.tab_challenge_selected,
            R.drawable.tab_find_selected,
            R.drawable.tab_bank_selected,
            R.drawable.tab_me_selected
    };

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private ThirdLoginUserInfo mThirdLoginUserInfo;
    private File file;
    private String mScheme;
    private int mCurrentTab = 0;
    private boolean firstStart = true;
    private NormalDialog permissionDialog;

    @AfterInject
    void initDI() {
        Injector.initMainActivityComponent().inject(this);
    }

    @AfterViews
    void init() {

        file = new File(Constants.THIRD_AVATAR_FILE);
        if (file.exists()) {
            file.delete();
        }

        Intent intent = getIntent();

        if (intent.getExtras() != null) {
            mThirdLoginUserInfo = Parcels.unwrap(intent.getParcelableExtra(ThirdLoginUserInfo.EXTRA_NAME));
            boolean isNew = intent.getBooleanExtra("isNew", true);
            mCurrentTab = intent.getIntExtra("currentTab",0);

            if (isNew) {
                setIcon();
                setName();
            }else {
                aHelper.getUserInfo(new MainGetUserInfoSubscriber());
            }
        }

        mFragmentList.add(ChallengeFragment_.builder().build());
        mFragmentList.add(FindFragment_.builder().build());
        mFragmentList.add(QuestionBankFragment_.builder().build());
        mFragmentList.add(MeFragment_.builder().build());

        //设置tab的标题、选中图标、未选中图标
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectedIds[i], mIconUnselectedIds[i]));
        }

        mTabLayout.setTabData(mTabEntities, this, R.id.layout_content, mFragmentList);

        setCurrentTab(mCurrentTab);

        String[] split = Utils.App.getAppVersionName().split("\\.");
        String versionName = mSharedPref.getString("versionName","");

        if (TextUtils.isEmpty(versionName) || !versionName.equals(split[0])) {
            mSharedPref.edit().putBoolean("firstScene", true).apply();
            mSharedPref.edit().putString("versionName", split[0]).apply();
            layoutGuide.setVisibility(View.VISIBLE);

        }else {
            layoutGuide.setVisibility(View.GONE);
        }


    }

    public void setCurrentTab(int index) {
        mTabLayout.setCurrentTab(index);
    }

    public void setName() {
        if (mThirdLoginUserInfo != null) {
            aHelper.setName(new MainSetUserInfoSubscriber(),mThirdLoginUserInfo.nickName);
        }
    }

    public void setIcon() {
        // 联网从第三方提供的头像url中将头像图片下载到本地
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder()
//                .url(mThirdLoginUserInfo.userIcon)
//                .build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                // 通过流转化为Bitmap类型文件,再写入本地
//                InputStream is = response.body().byteStream();
//                Bitmap bitmap = BitmapFactory.decodeStream(is);
//
//                FileOutputStream os = new FileOutputStream(file);
//                bitmap.compress(Bitmap.CompressFormat.PNG,100,os);
//                os.flush();
//                os.close();
//
//                RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),file);
//                Map<String, RequestBody> maps = new HashMap<>();
//                maps.put("file\"; filename=\"avatar.jpg\"",body);
//
//                // 上传图片
//                aHelper.uploadImg(new MainUpLoadImgSubscriber(),"avatar.jpg",maps,"App_UserImage");
//            }
//        });
    }

    void toChallengeTab() {
        mTabLayout.setCurrentTab(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mDoubleClickExitDetector.click()) {
            ApplicationHelper.getInstance().exit();
            super.onBackPressed();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);  //这一句必须的，否则Intent无法获得最新的数据
    }

    @Override
    public void onResume() {
        super.onResume();

//        if (!firstStart) {

        Intent intent = getIntent();
        Uri data = null;
        if (intent != null) {
            data = intent.getData();
            setIntent(null);
        }
        if (data != null) {
            mScheme = data.toString();
        }
//        Utils.UI.showToastShort(mScheme);

        if (!TextUtils.isEmpty(mScheme)) {
            Intent intentScheme = new Intent();
            if (mScheme.contains("wrong/")) {
                mScheme = "";
                // 错题本首页
                setCurrentTab(2);
            }else if (mScheme.contains("news/")) {
                mScheme = "";
                // 发现首页
                setCurrentTab(1);
            }else if (mScheme.contains("lib/")) {
                mScheme = "";
                // 图索实验室
                intentScheme.setClass(this, LabActivity_.class);
                startActivity(intentScheme);
            }else if (mScheme.contains("scene/")) {
                // 场景详情
                String sceneStr = mScheme.substring(mScheme.lastIndexOf("/") + 1);
                mScheme = "";
                SceneList.Scene scene = new SceneList.Scene();
                scene.Id = Integer.valueOf(sceneStr);
                intentScheme.setClass(this, SceneDetailActivity_.class);
                intentScheme.putExtra(SceneList.Scene.EXTRA_NAME, Parcels.wrap(scene));
                startActivity(intentScheme);
            }else if (mScheme.contains("topic/")) {
                // 发现主题页
                String topicId = mScheme.substring(mScheme.lastIndexOf("/") + 1);
                mScheme = "";
                String topicUrl = Constants.WEB_PAGE_FIND_HOST + "cmsview/views/detail.html?id=" + topicId;
                intentScheme.setClass(this, PageDetailActivity_.class);
                intentScheme.putExtra("url",topicUrl);
                startActivity(intentScheme);
            }
        }
//        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    ) {
                if (permissionTip) {
                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
                    requestPermissions(new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    }, APP_PERMISSION);
                }

            } else {
                Utils.routineCheckVersion(this, mCurrentUser.getLatestAppVersion(), mCurrentUser.getAppDownloadUrl(), mCurrentUser.hasAppForcedUpdate(), mSharedPref);
            }
        } else {
            Utils.routineCheckVersion(this, mCurrentUser.getLatestAppVersion(), mCurrentUser.getAppDownloadUrl(), mCurrentUser.hasAppForcedUpdate(), mSharedPref);
        }

        Utils.routineCheckVersion(this, mCurrentUser.getLatestAppVersion(), mCurrentUser.getAppDownloadUrl(), mCurrentUser.hasAppForcedUpdate(), mSharedPref);
    }

    @Override
    protected void onDestroy() {
        DialogUtils.dismissAllDialog();
        if (permissionDialog != null) {
            permissionDialog.superDismiss();
            permissionDialog = null;
        }
        super.onDestroy();
    }

    @Override public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions,grantResults);

        permissionTip = false;

        switch(requestCode)
        {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case APP_PERMISSION:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if(!granted) {
                    // 没有获取到权限，做特殊处理
                    showDisablePermissionDialog();
                }else {
                    Utils.routineCheckVersion(this, mCurrentUser.getLatestAppVersion(), mCurrentUser.getAppDownloadUrl(), mCurrentUser.hasAppForcedUpdate(), mSharedPref);
                }
                break;
            default:
                break;
        }
    }

    private void showDisablePermissionDialog() {
        permissionDialog = new NormalDialog(this);

        permissionDialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content("无法使用自动更新功能\n请在\"设置\"中开启存储卡权限")
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("确定")
                .btnTextSize(15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .show();

        permissionDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
//                        IntentUtils.toSystemPermissionActivity(mActivity);
                permissionDialog.dismiss();
            }
        });

    }

    @Click(R.id.challenge_btn_close_guide)
    void hideGuideLayout() {
        layoutGuide.setVisibility(View.GONE);
    }

    @Background(delay = 3000)
    void delayToFinishApp() {
        finish();
        ApplicationHelper.getInstance().exit();
    }

    private class MainUpLoadImgSubscriber extends Subscriber<UploadResponse> {


        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(UploadResponse uploadResponse) {
            if (uploadResponse.checkState(MainActivity.this)) {
                if (uploadResponse.Total <= 0) {

                } else {
                    aHelper.setAvatar(new MainSetUserInfoSubscriber(),uploadResponse.Data.get(0));
                }
            }
        }
    }

    private class MainSetUserInfoSubscriber extends Subscriber<ApiResult> {

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(ApiResult apiResult) {
            file.delete();
        }
    }

    private class MainGetUserInfoSubscriber extends Subscriber<UserInfo> {


        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onNext(UserInfo userInfo) {
            if (TextUtils.isEmpty(userInfo.Photo) && TextUtils.isEmpty(userInfo.Name)) {
                setIcon();
                setName();
            }else if (!TextUtils.isEmpty(userInfo.Photo) && TextUtils.isEmpty(userInfo.Name)) {
                setName();
            }else if (TextUtils.isEmpty(userInfo.Photo) && !TextUtils.isEmpty(userInfo.Name)) {
                setIcon();
            }
        }
    }




}
